package com.renrenyou.duanshipin.tools;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.renrenyou.duanshipin.R;
import com.renrenyou.duanshipin.base.BaseActivity;
import com.renrenyou.duanshipin.databinding.ActivityPicZipBinding;
import com.renrenyou.duanshipin.util.FileSizeUtil;
import com.renrenyou.duanshipin.util.ProgressDialogUtil;
import com.renrenyou.duanshipin.util.StoragePermissionHelper;
import com.renrenyou.duanshipin.util.ToastUtil;

import java.io.File;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PicZipActivity extends BaseActivity<ActivityPicZipBinding> implements View.OnClickListener {

    private float mZipQuality = -1f;
    private final int PICK_IMAGE_REQUEST = 1000;
    private String mImageFilePath;
    private long mFileSize = 0L;

    @Override
    public ActivityPicZipBinding getBinding(LayoutInflater inflater) {
        return ActivityPicZipBinding.inflate(inflater);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.ivPicAdd.setOnClickListener(this);
        mBinding.tvPicHigh.setOnClickListener(this);
        mBinding.tvPicMiddle.setOnClickListener(this);
        mBinding.tvPicLow.setOnClickListener(this);
        mBinding.tvPicChange.setOnClickListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        StoragePermissionHelper.handlePermissionResult(this, requestCode, grantResults);

        if (requestCode == StoragePermissionHelper.STORAGE_PERMISSION_REQUEST_CODE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            performFileOperations();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri imageUri = data.getData();
            String filePath = imageUri.getPath();
            if (TextUtils.isEmpty(filePath)) {
                return;
            }
            Glide.with(this).load(imageUri).into(mBinding.ivPicPic);
            mBinding.gpPicAdd.setVisibility(View.INVISIBLE);
            mImageFilePath = FileSizeUtil.getRealPathFromUri(this, imageUri);
            mFileSize = FileSizeUtil.getAutoFileOrFilesSize(mImageFilePath);
            mBinding.tvPicOld.setText(FileSizeUtil.FormatFileSize(mFileSize));
        }
    }

    private void performFileOperations() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_pic_add) {
            if (!StoragePermissionHelper.hasStoragePermission(this)) {
                StoragePermissionHelper.requestStoragePermission(this);
            } else {
                // 已经有权限，执行文件操作
                performFileOperations();
            }
        } else if (v.getId() == R.id.tv_pic_high) {
            mZipQuality = 0.9f;
            mBinding.tvPicHigh.setSelected(true);
            mBinding.tvPicMiddle.setSelected(false);
            mBinding.tvPicLow.setSelected(false);
        } else if (v.getId() == R.id.tv_pic_middle) {
            mZipQuality = 0.5f;
            mBinding.tvPicHigh.setSelected(false);
            mBinding.tvPicMiddle.setSelected(true);
            mBinding.tvPicLow.setSelected(false);
        } else if (v.getId() == R.id.tv_pic_low) {
            mZipQuality = 0.3f;
            mBinding.tvPicHigh.setSelected(false);
            mBinding.tvPicMiddle.setSelected(false);
            mBinding.tvPicLow.setSelected(true);
        } else if (v.getId() == R.id.tv_pic_change) {
            composeImage();
        }
    }

    private AlertDialog mProgressDialog;

    private void composeImage() {
        if (mZipQuality == -1) {
            ToastUtil.showToast(this, "请选择压缩质量");
            return;
        }
        if (TextUtils.isEmpty(mImageFilePath)) {
            ToastUtil.showToast(this, "请选择要压缩的图片");
            return;
        }

        Luban.with(this)
                .load(mImageFilePath)
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
                .setTargetDir("/Download/Pictures")                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        mProgressDialog = ProgressDialogUtil.showProgressDialog(PicZipActivity.this);
                    }

                    @Override
                    public void onSuccess(File file) {
                        if (mProgressDialog != null) {
                            mProgressDialog.dismiss();
                        }
                        Log.d("piczipActivity", "onSuccess: 压缩成功");
                        ToastUtil.showToast(PicZipActivity.this, "压缩成功!");

                        mBinding.tvPicNew.setText(FileSizeUtil.FormatFileSize((long) (mFileSize * mZipQuality)));
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mProgressDialog != null) {
                            mProgressDialog.dismiss();
                        }
                        Log.d("piczipActivity", "onError: "+e.getMessage());
                        ToastUtil.showToast(PicZipActivity.this, "压缩成功!");

                        mBinding.tvPicNew.setText(FileSizeUtil.FormatFileSize((long) (mFileSize * mZipQuality)));
                    }
                }).launch();    //启动压缩

    }
}
